package org.hope.lee.web;

import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
import org.hope.lee.command.UserCollapseCommand;
import org.hope.lee.model.User;
import org.hope.lee.service.PeopleService;
import org.hope.lee.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.Future;

/**
 * Created by lisen on 2017/12/27.
 */
@RestController
public class CollapseCommandController {

    @Autowired
    private UserService userService;

    @Autowired
    private PeopleService peopleService;

    @RequestMapping(value = "/collapse", method = RequestMethod.GET)
    public void requestCollapse() {
        HystrixRequestContext context = HystrixRequestContext.initializeContext();
        try {
            Future<User> f1 = new UserCollapseCommand(userService, 1L).queue();
            Future<User> f2 = new UserCollapseCommand(userService, 2L).queue();
            Future<User> f3 = new UserCollapseCommand(userService, 3L).queue();

            Thread.sleep(3000);

            Future<User> f4 = new UserCollapseCommand(userService, 4L).queue();
            Future<User> f5 = new UserCollapseCommand(userService, 5L).queue();

            User u1 = f1.get();
            User u2 = f2.get();
            User u3 = f3.get();

            User u4 = f4.get();
            User u5 = f5.get();
            System.out.println(u1.getName());
            System.out.println(u2.getName());
            System.out.println(u3.getName());
            System.out.println(u4.getName());
            System.out.println(u5.getName());
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            context.close();
        }
    }

    @RequestMapping(value = "/collapse/annotation", method = RequestMethod.GET)
    @ResponseBody
    public void requestCollapseAnnotation() {
        HystrixRequestContext context = HystrixRequestContext.initializeContext();
        try {
            Future<User> f1 = peopleService.find(11L);
            Future<User> f2 = peopleService.find(12L);
            Future<User> f3 = peopleService.find(13L);

//            Thread.sleep(3000);

            Future<User> f4 = peopleService.find(14L);
            Future<User> f5 = peopleService.find(15L);

            System.out.println(f1.get().getName());
            System.out.println(f2.get().getName());
            System.out.println(f3.get().getName());
            System.out.println(f4.get().getName());
            System.out.println(f5.get().getName());

        }catch (Exception e) {
            e.printStackTrace();
        } finally {
            context.close();
        }


    }

}
